/*
    下发作业
*/
import React, { useState } from 'react';
import { DatePicker, Input, message } from 'antd';
import { Form } from 'antd';
import { Space } from 'antd';
import style from './index.less';
import { Select, Modal, Upload } from 'antd';
import { Button } from 'antd';
import { Table } from 'antd';
import { Link } from 'react-router-dom';
import request from '@/http';
import constant from '@/constant';
import CONSTANT from '@/constant';
import SecurityService from '@/service/securityService';
import { UploadOutlined } from '@ant-design/icons';
import RichEditor from '../../../../components/richEditor';

import moment from 'moment';
import All_style from '../../../index.less';

const { Option } = Select;
const { RangePicker } = DatePicker;

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 16 },
};

const Issue = (prop: any) => {
  const columns = [
    {
      title: '提交时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      // render: text => <a>{text}</a>,
    },
    {
      title: '项目名称',
      dataIndex: 'courseName',
      key: 'courseName',
      align: 'center',
      //   render: text => <a>{text}</a>,
    },
    {
      title: '作业主题',
      dataIndex: 'title',
      key: 'title',
      align: 'center',
      // render: text => <a>{text}</a>,
    },
    {
      title: '作业类型',
      dataIndex: 'workType',
      key: 'workType',
      align: 'center',
    },
    {
      title: '实训老师',
      dataIndex: 'teacherName',
      key: 'teacherName',
      align: 'center',
    },
    {
      title: '计划完成时间',
      dataIndex: 'completeDate',
      key: 'completeDate',
      align: 'center',
    },
    {
      title: '小组',
      dataIndex: 'teamName',
      key: 'teamName',
      align: 'center',
    },
    {
      title: '学生总数',
      dataIndex: 'studentSum',
      key: 'studentSum',
      align: 'center',
    },
    {
      title: '待提交',
      dataIndex: 'daiTiJiao',
      key: 'daiTiJiao',
      align: 'center',
    },
    {
      title: '待批复',
      dataIndex: 'daiPiFu',
      key: 'daiPiFu',
      align: 'center',
    },
    {
      title: '已批复',
      dataIndex: 'yiPiFu',
      key: 'yiPiFu',
      align: 'center',
    },
    {
      title: '操作',
      // key: 'action',
      render: (row: any) => (
        <>
          <Link
            to={
              {
                //pathname: '/Teacher/Assignment/Issue/details',
                //state: { workId: row.workId },
              }
            }
          >
            <Button
              type="link"
              onClick={() => {
                // setCurrentEditObject({
                //   ...row,
                //   isModalVisible: true,
                // })
              }}
            >
              查看
            </Button>
          </Link>
          <Link
            to={
              {
                //pathname: '/Teacher/Assignment/Issue/index',
                //state: { workId: row.workId, teamName: row.group },
              }
            }
          >
            <Button type="link" onClick={deleteWork}>
              删除
            </Button>
          </Link>
        </>
      ),
    },
  ];

  const [formObjectForEdit] = Form.useForm();
  const [taskFileList, setTaskFileList] = React.useState<any>([]);
  const [modalEditor, setModalEditor] = React.useState<any>({
    isModalVisible: false,
    id: null,
  });
  //新增作业
  const initModalEditor = (isModalVisible: any, row: any) => {
    let id = null;
    if (row) {
      const taskFileList = row.taskFileList.map((file: any) => {
        return {
          name: file.name,
          url: CONSTANT.SERVER_ADDR + file.url,
          fileNo: file.fileNo,
        };
      });
      setTaskFileList(taskFileList);
      setModalEditor({
        ...row,
        taskType: row.taskType.code,
        finishTime: moment(row.finishTime, 'yyyy-MM-DD HH:mm:ss'),
        isModalVisible: isModalVisible,
      });
    } else {
      setTaskFileList([]);
      setModalEditor({
        isModalVisible: isModalVisible,
        id: null,
        // courseName: courseObject?.courseName,
        // projectName: courseObject?.projectName,
      });
    }
  };
  const modelOnCancel = () => {
    initModalEditor(false, null);
  };

  const modelOnOk = async () => {
    // if (!courseObject) {
    //   message.error('课程信息丢失');
    //   return;
    // }
    // if (!courseObject.courseId) {
    //   message.error('课程信息丢失');
    //   return;
    // }
    // const data = await formObjectForEdit.validateFields();
    // try {
    //   let action = constant.ACTION_EDIT;
    //   if (modalEditor.id === null || modalEditor.id === undefined) {
    //     action = constant.ACTION_CREATE;
    //   }
    //   const requestData = {
    //     ...data,
    //     id: modalEditor.id,
    //     [constant.ACTION_KEY]: action,
    //     courseId: courseObject.courseId,
    //     finishTime: data.finishTime.format('YYYY-MM-DD HH:mm:ss'),
    //   };
    //   taskFileList.map((file: any, index: any) => {
    //     requestData[`taskFileList[${index}].name`] = file.name;
    //     requestData[`taskFileList[${index}].fileNo`] = file.fileNo;
    //   });
    //   const result: any = await request.post('/admin/task/save', requestData);
    //   if (result.success) {
    //     if (action === constant.ACTION_CREATE) {
    //       message.success('数据添加成功');
    //     } else {
    //       message.success('数据修改成功');
    //     }
    //     initModalEditor(false, null);
    //     pageOnChange({
    //       ...pagination,
    //     });
    //   }
    // } catch (e) {
    //   message.error(e.message);
    // }
  };

  const deleteWork = async () => {
    let workid;
    let teamName;
    if (prop.location && prop.location.state) {
      workid = prop.location.state.workId;
      teamName = prop.location.state.teamName;
    }
    console.log(teamName);
    const deleteWork: any = await request.post(
      '/homeWork_manager_module/teacher/deleteHomeWork',
      {
        workId: workid,
        teamName: teamName,
      },
    );
  };
  const [formObject] = Form.useForm();
  const [captchaUrl, setCaptchaUrl] = React.useState('');

  // 项目名称下拉框绑定接口
  const [courseId, setCourseId] = React.useState();
  const [courseName, setCourseName] = React.useState([]);
  const CourseName = async () => {
    const CourseName: any = await request.post('/common/getCourse', {
      isGraduation: 1,
    });
    console.log(CourseName.date);
    setCourseName(CourseName.date);
    //setCourseId(CourseName.date.id);
  };

  //项目组下拉栏（查询所有项目组）
  const [groupId, setGroupId] = React.useState();
  const [projectSearchValue, setProjectSearchValue] = React.useState('');
  const searchProjectOnChange = (value: any) => {
    setProjectSearchValue(value.target.value);
  };
  const [group, setGroup] = React.useState([]);
  const getGroup = async () => {
    const Group: any = await request.post('/team/selectTeam', {
      isGraduation: 1,
      teamName: projectSearchValue,
      page: 1,
      number: 10,
    });
    console.log(Group);
    if (Group.code == '200') {
      setGroup(Group.date.returnDate);
      //setGroupId(Group.date.returnDate.teamInfoId)
      //selGroup(Group.date.returnDate[0].teamInfoId);
    } else {
      message.error(Group.message); //弹出错误信息
    }
  };
  // 实训老师下拉框绑定接口
  const [teacherId, setTeacherId] = React.useState();
  const [trTeacherName, setTrTeacherName] = React.useState([]);
  const TrTeacherName = async () => {
    const TrTeacherName: any = await request.get(
      // '/user_info_manage/getTrTeacherName',
      '/common/getTrainingTeacher',
    );
    // console.log(TrTeacherName.data);
    setTrTeacherName(TrTeacherName.date);
    //setTeacherId(TrTeacherName.date.id);
    console.log(trTeacherName);
  };
  // 作业类型下拉框接口绑定
  const [workType, setWorkType] = React.useState([]);
  const WorkType = async () => {
    const WorkType: any = await request.put('/user_info_manage/getWorkType');
    setWorkType(WorkType.data);
  };

  //01
  // 条件查询教师下发作业表绑定接口
  const [data, setData] = React.useState<any>();
  interface pay {
    current: number;
    pageSize: number;
    total: number;
    onChange: any;
  }
  // const onCurrentChange = (page, pageSize) => {
  //   loadData(page, pageInfo.pageSize);
  // };
  // const [pageInfo, setPageInfo] = useState<pay>({
  //   current: 1,
  //   pageSize: 2,
  //   total: 0,
  //   onChange: onCurrentChange,
  // });

  const loadData = async () => {
    const selectForm = await formObject.validateFields(); //获得表单数据
    // 处理日期数据
    console.log('处理日期数据', selectForm);
    const createTime = selectForm?.createTime
      ? selectForm?.createTime?.format('YYYY-MM-DD hh:mm:ss')
      : '';
    const completeDate = selectForm?.completeDate
      ? selectForm?.completeDate?.format('YYYY-MM-DD hh:mm:ss')
      : '';
    // console.log(workPubTime)
    const result: any = await request.post(
      '/work-info-entity/selectHomeworkInfo', //连接接口
      {
        completeDate: completeDate,
        courseId: selectForm.courseName,
        teamInfoId: selectForm.teamName,
        title: selectForm.title,
        workType: selectForm.workType,
        createTime: createTime,
        teacherId: selectForm.teacherName,
      },
    );
    console.log('查询教师下发作业表', result.date);
    if (result.code === '200') {
      console.log('kjjk');
      const newData = result.date.map((d: any) => {
        return {
          id: d.id,
          title: d.title,
          completeDate: d.completeDate,
          workType: d.workType,
          courseName: d.courseName,
          teamName: d.teamName,
          workId: d.workId,
          createTime: d.createTime,
          daiPiFu: d.daiPiFu,
          daiTiJiao: d.daiTiJiao,
          yiPiFu: d.yiPiFu,
          studentSum: d.studentSum,
          teacherName: d.teacherName,
        };
      });
      setData(newData);
    } else {
      message.error(result.message);
      setData(null);
    }
  };
  // 重置按钮
  const onReset = () => {
    formObject.resetFields();
    console.log('重置成功');
  };
  // 页面预加载
  React.useEffect(() => {
    TrTeacherName();
    CourseName();
    //TeamName();
    getGroup();
    // WorkType();
    loadData();
  }, []);

  return (
    <div className={All_style.box}>
      <Form form={formObject} preserve={false}>
        <div style={{ clear: 'both' }}>
          <Form.Item
            label={'发布时间：'}
            name="createTime"
            style={{ float: 'left' }}
            className={All_style.data}
          >
            <RangePicker
              format="YYYY-MM-DD HH:mm:ss"
              showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}
              className={All_style.select}
            ></RangePicker>
          </Form.Item>

          <Form.Item
            label={'作业主题：'}
            name="title"
            style={{ float: 'left' }}
            className={All_style.formItem}
          >
            <Input
              placeholder="请输入作业主题"
              className={All_style.select}
            ></Input>
          </Form.Item>

          <Form.Item
            label="项目名称："
            name="courseName"
            style={{ float: 'left' }}
            className={All_style.formItem}
          >
            <Select
              allowClear
              placeholder="请选择"
              className={All_style.select}
              optionFilterProp="children"
              showSearch
            >
              {courseName.map((c: any, index) => {
                return (
                  <Option key={c.id} value={c.id}>
                    {c.format}
                  </Option>
                );
              })}
            </Select>
          </Form.Item>
        </div>
        <div style={{ clear: 'both' }}>
          <Form.Item
            name="teamName"
            label="小组选择"
            style={{ float: 'left' }}
            className={All_style.formItem}
          >
            <Select placeholder="请选择" className={All_style.select}>
              {group.map((c: any, index) => {
                return (
                  <Option key={`k_${index}`} value={c.teamInfoId}>
                    {c.teamName}
                  </Option>
                );
              })}
            </Select>
          </Form.Item>

          <Form.Item
            label={'计划完成时间:'}
            name="completeDate"
            style={{ float: 'left' }}
            className={All_style.data}
          >
            <RangePicker
              format="YYYY-MM-DD HH:mm:ss"
              showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}
              className={All_style.select}
            ></RangePicker>
          </Form.Item>

          <Form.Item
            label="实训老师："
            name="teacherName"
            style={{ float: 'left' }}
            className={All_style.formItem}
          >
            <Select
              allowClear
              placeholder="请选择"
              className={All_style.select}
              optionFilterProp="children"
              showSearch
            >
              {trTeacherName.map((c: any) => {
                return (
                  <Option key={c.id} value={c.id}>
                    {c.format}
                  </Option>
                );
                //setTeacherId(c.id);
              })}
            </Select>
          </Form.Item>
        </div>
        <div style={{ clear: 'both' }}>
          <Form.Item
            label={'作业类型:'}
            name="workType"
            style={{ float: 'left' }}
            className={All_style.formItem}
          >
            <Select
              allowClear
              placeholder="请选择"
              className={All_style.select}
              optionFilterProp="children"
              showSearch
            >
              {workType.map((c, index) => {
                return (
                  <Option key={`k_${index}`} value={c}>
                    {c}
                  </Option>
                );
              })}
            </Select>
          </Form.Item>

          <Button
            onClick={() => loadData()}
            htmlType="button"
            className={All_style.button}
          >
            查询
          </Button>
          <Button
            htmlType="button"
            onClick={onReset}
            className={All_style.button2}
          >
            重置
          </Button>
        </div>
      </Form>

      <div style={{ clear: 'both' }}>
        <Button
          style={{ marginBottom: '20px' }}
          type="primary"
          className={All_style.button}
          onClick={() => {
            initModalEditor(true, null);
          }}
        >
          +新增作业
        </Button>
        <Table
          columns={columns}
          dataSource={data}
          className={All_style.table}
          //pagination={pageInfo}
        />
      </div>

      <Modal
        width={1000}
        title={modalEditor.id ? '编辑' : '新增'}
        visible={modalEditor.isModalVisible}
        onCancel={modelOnCancel}
        onOk={modelOnOk}
        maskClosable={false}
        destroyOnClose
        okText="确认"
        cancelText="取消"
      >
        <Form
          {...layout}
          name="editForm"
          form={formObjectForEdit}
          preserve={false}
        >
          <Form.Item label="课程名称" name="courseName">
            <Input placeholder="请输入课程名称..." readOnly disabled />
          </Form.Item>
          <Form.Item label="项目名称" name="projectName">
            <Input placeholder="请输入项目名称..." readOnly disabled />
          </Form.Item>
          <Form.Item
            label="作业主题"
            name="title"
            rules={[
              {
                required: true,
                whitespace: true,
                message: '作业主题不能为空!',
              },
              { max: 30, message: '最大长度不能超过30!' },
            ]}
          >
            <Input placeholder="请输入作业主题..." />
          </Form.Item>
          <Form.Item
            label="完成时间"
            name="finishTime"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <DatePicker showTime format={'YYYY-MM-DD HH:mm:ss'} />
          </Form.Item>
          <Form.Item
            label="作业类型"
            name="taskType"
            rules={[{ required: true, message: '作业类型不能为空!' }]}
          >
            <Select>
              <Option value="">请选择...</Option>
              <Option value="PERSONAL">日常作业</Option>
              <Option value="PROJECT">阶段作业</Option>
              <Option value="FINISH">最终作业</Option>
            </Select>
          </Form.Item>
          <Form.Item label="上传相关附件">
            <Upload
              name={'ofile'}
              action={CONSTANT.SERVER_ADDR + '/ofile/upload'}
              headers={{
                token: (function () {
                  const user = SecurityService.getSecurity();
                  return user ? (user.token ? user.token : '') : '';
                })(),
              }}
              data={{ ofile_class_code: 'teacherFile' }}
              fileList={taskFileList}
              onChange={(info) => {
                let fileList = [...info.fileList];
                fileList = fileList.map((file) => {
                  const fileNew: any = {
                    ...file,
                  };
                  if (fileNew.status === 'done') {
                    const result = file.response;
                    if (result && result.success) {
                      fileNew.url = `${CONSTANT.SERVER_ADDR}${result.data.url}`;
                      fileNew.fileNo = result.data.resNo;
                    }
                  }
                  return fileNew;
                });
                setTaskFileList(fileList);
              }}
            >
              <Button icon={<UploadOutlined />}>选择上传文件。。。</Button>
            </Upload>
          </Form.Item>
          <Form.Item
            label="作业详情"
            name="content"
            rules={[{ required: true, message: '详情不能为空!' }]}
          >
            <RichEditor />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Issue;
